﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using NodeBasedSkillEditor.ViewModel;

namespace NodeBasedSkillEditor.View
{
    public class NodeCanvas : Canvas
    {
        public float Zoom {
            get { return (float)GetValue(ZoomProperty); }
            set { SetValue(ZoomProperty, Math.Clamp(value, VM_DAG.MinZoom, VM_DAG.MaxZoom)); }
        }
        public static readonly DependencyProperty ZoomProperty =
            DependencyProperty.Register("Zoom", typeof(float), typeof(NodeCanvas),
                new PropertyMetadata(1f, OnZoomPropertyChanged));

        public Vector Pan {
            get { return (Vector)GetValue(PanProperty); }
            set { SetValue(PanProperty, value); }
        }

        public static readonly DependencyProperty PanProperty =
            DependencyProperty.Register("Pan", typeof(Vector), typeof(NodeCanvas),
                new PropertyMetadata(new Vector(), OnPanPropertyChanged));

        ScaleTransform _scale = new ScaleTransform(1.0, 1.0);
        TranslateTransform _translate = new TranslateTransform();

        static NodeCanvas()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(NodeCanvas), new FrameworkPropertyMetadata(typeof(NodeCanvas)));
        }

        public NodeCanvas()
        {
            var transGroup = new TransformGroup();
            transGroup.Children.Add(_scale);
            transGroup.Children.Add(_translate);
            RenderTransform = transGroup;
        }

        void OnZoomChanged()
        {
            _scale.ScaleX = Zoom;
            _scale.ScaleY = Zoom;
        }

        static void OnZoomPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var s = sender as NodeCanvas;
            s.OnZoomChanged();
        }

        void OnPanChanged()
        {
            _translate.X = Pan.X;
            _translate.Y = Pan.Y;
        }

        static void OnPanPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var s = sender as NodeCanvas;
            s.OnPanChanged();
        }

        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);
        }

    }
}
